// websocket连接
import { reactive, ref } from "vue";
import Role from "./role";
import { downKeyMove, rescue } from "./downKey"; // 键盘事件
import { createStone } from "./stone"; //创建障碍物
import Pointer from "./pointer";
import Bomb from "./bomb";
import Comment from "./comment";
import { bombArr2 } from "./bomb";
import stoneArr from "./stone";
import Stage, { stageArr } from "./stage";

let roleArr = ref([]); //人物数组
let bombArr = ref([]); //炸弹数组 装的是格子序号
export let propsArr = reactive({
  shoes: [], //加速鞋子
  bomb: [] //炸弹加威力
}); //装道具出现位置
let pointer = new Pointer();
let bomb = new Bomb();
let stages = new Stage();
export const linkType = ref(0); //返回的消息 messageType
export let socket = null;
export let myName = ""; //我当前创建的角色
export function link() {
  let _Role = new Role(); //获取创建角色方法
  if (typeof WebSocket == "undefined") {
    console.log("您的浏览器不支持WebSocket");
  } else {
    console.log("您的浏览器支持WebSocket");
    //实现化WebSocket对象，指定要连接的服务器地址与端口  建立连接
    //等同于socket = new WebSocket("ws://localhost:8888/xxxx/im/25");
    //var socketUrl="${request.contextPath}/im/"+$("#userId").val();
    let socketUrl = "ws://10.118.12.46:2666/ws";
    socketUrl = socketUrl.replace("https", "ws").replace("http", "ws");
    if (socket != null) {
      socket.close();
      socket = null;
    }
    socket = new WebSocket(socketUrl);
    //打开事件  websocket已打开 messageType==0初始化地图
    socket.onopen = function() {
      socket.send("{messageType:" + 0 + ",sequenceId:" + 1 + "}");
    };
    //获得消息事件
    socket.onmessage = function(msg) {
      let msgData = JSON.parse(msg.data);
      console.log("收到消息:", msgData);
      // messageType==1  代表新的一个角色创建
      if (msgData.messageType == 1) {
        _Role.create(
          msgData.gameRole.x,
          msgData.gameRole.y,
          msgData.userRole.name
        );
        myName = msgData.userRole.name;
        createStone(msgData.map.cells); //创建障碍物
        pointer.create(msgData.gameRole.x, msgData.gameRole.y, myName); // 创建指针
        // 6 是发送准备消息  7 是收到服务器 玩家准备好消息
        socket.send("{messageType:" + 6 + ",sequenceId:" + 1 + "}");
        roleArr.value.push({
          name: msgData.userRole.name,
          x: msgData.gameRole.x,
          y: msgData.gameRole.y
        });
      }
      // messageType==9  显示其他的角色
      if (msgData.messageType == 9) {
        msgData.roleList.map(item => {
          if (item.userRole.name && item.userRole.name !== myName) {
            let x = item.gameRole.x;
            let y = item.gameRole.y;
            _Role.create(x, y, item.userRole.name);
          }
        });
      }
      // messageType==8  知道别人移动距离  显示最新距离
      if (msgData.messageType == 8) {
        let oBox = document.querySelector(`.${msgData.name}`);
        _Role.move(oBox, msgData.x, msgData.y);
      }
      // messageType==12  知道谁 断开链接
      if (msgData.messageType == 12) {
        let oBox = document.querySelector(`.${msgData.name}`);
        oBox ? _Role.remove(oBox) : "";
      }
      // messageType==13 炸弹位置信息
      if (msgData.messageType == 13) {
        let obj = bomb.create(msgData);
        bombArr.value.push(obj);
      }
      // messageType==3 炸弹爆炸响应
      if (msgData.messageType == 3) {
        msgData.bombNos.map(item => {
          let zdCenter = document.getElementById(`zd-${item}`);
          let x = (item % 24) * Comment.bombWidth;
          let y = parseInt(item / 24) * Comment.bombHeight;
          if (zdCenter) {
            zdCenter.style.width = Comment.bombWidth + "px";
            zdCenter.style.height = Comment.bombHeight + "px";
            zdCenter.src = Comment.bombImg;
            setTimeout(() => {
              document.getElementById("box").removeChild(zdCenter);
              bombArr2.map((i, index) => {
                if (i[0] == x && i[1] == y) {
                  bombArr2.splice(index, 1);
                }
              });
            }, 300);
          } else {
            let zd = document.createElement(`img`);
            zd.setAttribute("id", `zd-${item}`);
            zd.style.left = x + "px";
            zd.style.top = y + "px";
            zd.style.width = Comment.bombWidth + "px";
            zd.style.height = Comment.bombHeight + "px";
            zd.style.position = "absolute";
            zd.src = Comment.bombImg;
            document.getElementById("box").appendChild(zd);
            setTimeout(() => {
              document.getElementById("box").removeChild(zd);
            }, 300);
          }
        });
      }
      // messageType==7 玩家准备好响应
      if (msgData.messageType == 7) {
        downKeyMove(myName); //设置键盘移动事件
      }
      // messageType==14 人物被炸到响应 等待救援
      if (msgData.messageType == 14) {
        if (myName == msgData.userName) {
          rescue.value = true;
        }
        let _P = document.createElement("img");
        _P.src = require(`@/assets/paopao.png`);
        _P.id = `paopao-${msgData.userName}`;
        _P.style.width = Comment.roleWidth + "px";
        _P.style.height = Comment.roleHeight + "px";
        _P.style.position = "absolute";
        _P.style.top = msgData.gameRole.y - Comment.roleWidth / 2 + "px";
        _P.style.left = msgData.gameRole.x - Comment.roleHeight / 2 + "px";
        _P.style.zIndex = "3";
        document.getElementById("box").appendChild(_P);
      }
      // messageType==15 人物死亡
      if (msgData.messageType == 15) {
        console.log(msgData.userRoleName, "你已经死亡");
        let r = document.querySelector(`.${msgData.userRoleName}`); //人物
        let oPointer = document.querySelector(
          `.pointer-${msgData.userRoleName}`
        ); // 指针
        let pao = document.getElementById(`paopao-${msgData.userRoleName}`); //泡泡
        document.getElementById("box").removeChild(r);
        oPointer ? document.getElementById("box").removeChild(oPointer) : "";
        document.getElementById("box").removeChild(pao);
      }
      //  messageType==19 箱子xz障碍物炸毁
      if (msgData.messageType == 19) {
        msgData.boxNos.map(item => {
          let x = (item % 24) * Comment.blockSize;
          let y = parseInt(item / 24) * Comment.blockSize;
          let xz = document.getElementById(`xz-${item}`);
          stoneArr.xz.map((item2, index2) => {
            if (item2[0] == x && item2[1] == y) {
              stoneArr.xz.splice(index2, 1);
            }
          });
          document.getElementById("box").removeChild(xz);
        });
      }
      //  messageType==11 随机道具生成
      if (msgData.messageType == 11) {
        msgData.props.map(item => {
          let x = (item.cellNo % 24) * Comment.blockSize;
          let y = parseInt(item.cellNo / 24) * Comment.blockSize;
          switch (item.propType) {
            case 4:
              stages.create(
                x,
                y,
                item.cellNo,
                item.propType,
                require("../../assets/speed.png")
              );
              break;
            case 5:
              stages.create(
                x,
                y,
                item.cellNo,
                item.propType,
                require("../../assets/bombNum.png")
              );
              break;
            case 6:
              stages.create(
                x,
                y,
                item.cellNo,
                item.propType,
                require("../../assets/power.png")
              );
              break;
          }
        });
      }
      // messageType == 21 谁捡到道具
      if (msgData.messageType == 21) {
        stageArr.value.map((item, index) => {
          if (item[3] == msgData.prop.cellNo) {
            let s = document.getElementById(`stage-${msgData.prop.cellNo}`); //移除道具
            document.getElementById("box").removeChild(s);
            stageArr.value.splice(index, 1);
          }
        });
      }
      // messageType == 5 游戏结束
      if (msgData.messageType == 5) {
        var r = confirm("游戏结束了");
        if (r == true) {
          window.location.reload();
        } else {
          window.location.reload();
        }
      }
    };
    //关闭事件
    socket.onclose = function() {
      console.log("websocket已关闭");
    };
    //发生了错误事件
    socket.onerror = function() {
      console.log("websocket发生了错误");
    };
  }
}
